/*
 * Copyright (c) 2006-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.livejournal;

import java.awt.BorderLayout;
import java.awt.Component;
import java.util.EventObject;

import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.jdesktop.swingx.JXStatusBar;
import org.jdesktop.swingx.plaf.basic.BasicStatusBarUI;
import org.panteleyev.blogclient.BloggerFrame;
import org.panteleyev.blogclient.Icon;
import org.panteleyev.blogclient.Options;
import org.panteleyev.fotobilder.FBAccount;
import org.panteleyev.fotobilder.FBAccountInfo;
import org.panteleyev.fotobilder.FBGallery;
import org.panteleyev.livejournal.events.PhotosUpdatedEvent;
import org.panteleyev.swing.MenuProvider;
import org.panteleyev.swing.SwingFactory;
import org.panteleyev.swing.ToolBarProvider;
import org.panteleyev.utilities.events.AppEventListener;

/**
 *
 * @author  Petr Panteleyev
 */
public class FotoBilderFrame extends BloggerFrame<LJUserProfile> {
    private JTabbedPane     tabs;
    private JLabel          statusLabel;
    private int             busy;
    private JToolBar        panelToolBar;
    private FBAccount       fbAccount;

    public FotoBilderFrame(LJUserProfile profile) {
        super(profile);

        fbAccount = profile.getFbAccount();
        createActions();
        initComponents();

        setDefaultStatusLabel();

        setIconImage(Icon.GALLERIES.I().getImage());
        Options.getBounds(this);

        addAppEventListener(PhotosUpdatedEvent.class, new AppEventListener() {
            @Override
            public void eventReceived(EventObject event) {
                onUpdatePictures();
            }
        });

    }

    private void createActions() {
    }

    private void initComponents() {
        getContentPane().setLayout(new BorderLayout());
        setTitle(L10N.FBF_TITLE.s());

        tabs = new JTabbedPane();
        FotoBilderListPanel panel = new FotoBilderListPanel(this, getProfile());
        tabs.add(L10N.FBF_ALBUMS_TAB_TITLE.s(), panel);

        getContentPane().add(SwingFactory.createToolBarPanel(
            panelToolBar = SwingFactory.createToolBar(false, true,
                panel.getToolBarActions()
            ),
            Box.createHorizontalStrut(5),
            createProfileToolBar(false, true),
            Box.createHorizontalGlue(),
            getBusyLabel(),
            Box.createHorizontalStrut(5)
        ), BorderLayout.NORTH);

        getContentPane().add(tabs, BorderLayout.CENTER);

        tabs.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent evt) {
                tabbedPaneStateChanged(evt);
            }
        });

        createMenuBar(
            createFileMenu(),
            panel.getMenu(),
            createProfileMenu(),
            createToolsMenu(),
            createWindowMenu(),
            createHelpMenu()
        );

        // Status Bar
        JXStatusBar statusBar = new JXStatusBar();
        statusBar.putClientProperty(BasicStatusBarUI.AUTO_ADD_SEPARATOR, false);
        JXStatusBar.Constraint c1 = new JXStatusBar.Constraint(JXStatusBar.Constraint.ResizeBehavior.FILL);
        statusBar.add(statusLabel = new JLabel());
        getContentPane().add(statusBar, BorderLayout.SOUTH);
    }


    private void setDefaultStatusLabel() {
        FBAccountInfo inf = fbAccount.getInfo();
        if (inf == null) {
            throw new IllegalStateException();
        }

        final StringBuilder b = new StringBuilder("Space used: ");
        b.append(String.format("%s/%s", inf.getQuotaUsed(), inf.getQuotaTotal()));

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                statusLabel.setText(b.toString());
            }
        });
    }

    private void tabbedPaneStateChanged(ChangeEvent evt) {
        Component comp = tabs.getSelectedComponent();

        if (comp instanceof MenuProvider) {
            Component c = getJMenuBar().getComponent(1);
            c.setVisible(false);
            JMenu menu = ((MenuProvider)comp).getMenu();
            menu.setVisible(true);
            getJMenuBar().remove(1);
            getJMenuBar().add(menu, 1);
        }

        if (comp instanceof ToolBarProvider) {
            panelToolBar.removeAll();
            SwingFactory.fill(panelToolBar, ((ToolBarProvider)comp).getToolBarActions());
        }
    }

    void onOpenGallery(FBGallery gallery) {
        // check if this set is already open
        for (Component comp : tabs.getComponents()) {
            if (comp instanceof FotoBilderGalleryPanel) {
                if (((FotoBilderGalleryPanel)comp).getGallery() == gallery) {
                    tabs.setSelectedComponent(comp);
                    return;
                }
            }
        }

        FotoBilderGalleryPanel panel = new FotoBilderGalleryPanel(this, getProfile(), gallery);
        tabs.add(gallery.getTitle(), panel);
        tabs.setSelectedComponent(panel);
    }

    private void onUpdatePictures() {
        for (Component comp : tabs.getComponents()) {
            if (comp instanceof FotoBilderGalleryPanel) {
                ((FotoBilderGalleryPanel)comp).update();
            }
        }
    }

}
